<template>
  <div class="daily-work">
    <div
      class="daily-work-pc"
      :style="{
        display: pcDisplay,
      }"
    >
      <LinearButton>
        <template #buttonText>primary</template>
      </LinearButton>

      <FlashButton></FlashButton>
      <SendButton></SendButton>
      <div class="wrapper flex-column">
        <div class="title">
          <span>每日计划</span>
        </div>
        <div class="content-wrap flex">
          <div class="calendar pl-15 pr-15 pb-15">
            <div class="month-year flex">
              <div class="month-info">
                <div class="month">
                  <img src="../../assets/images/flag.svg" />
                  <span class="month-text">{{ currentMonth }}</span>
                </div>
                <div class="month-text-chinese">{{ currentMonthText }}</div>
              </div>
              <div class="year">
                {{ currentYear }}
              </div>
            </div>
            <div class="weekday flex">
              <div
                v-for="(item, index) of weekList"
                :class="[
                  'weekday-item',
                  {
                    weekend: [5, 6].includes(index),
                    'ml-5': index !== 0,
                  },
                ]"
                :key="item"
              >
                周{{ item }}
              </div>
            </div>

            <div class="days flex">
              <div
                v-for="(item, index) of days"
                :class="[
                  'day-item mt-5 pl-5',

                  {
                    active: currentDate === item.completeDay,
                    'ml-5': index % 7 !== 0,
                  },
                ]"
                :key="item.completeDay"
                @click="setDay(item)"
                :style="{
                  color: item.currentMonth ? '' : '#f5e7cb',
                  backgroundColor: item.currentMonth ? '' : '#fff',
                }"
              >
                <div class="day-status flex-column-center pr-5">
                  <span class="day">{{ item.day }}</span>
                  <template v-if="item.day <= todayValue">
                    <a-tooltip v-if="item.status === 1" color="green">
                      <template #title>计划都完成啦!</template>
                      <CheckOutlined />
                    </a-tooltip>
                    <a-tooltip v-else-if="item.status === 0" color="red">
                      <template #title>好像有些遗漏哦~</template>
                      <FrownOutlined />
                    </a-tooltip>
                  </template>
                </div>
                <div class="todo-num">
                  <i class="iconfont icon--Todo-List"></i>
                  <span>{{ item.num || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="todo-list flex-column" :style="todoStyle">
            <div
              class="tips mb-10"
              v-if="todoList && todoList.length !== 0"
              :style="{
                color: todoStatus[currentStatus].color,
              }"
            >
              {{ todoStatus[currentStatus].text }}
            </div>
            <div class="flex">
              <a-textarea
                v-model:value="taskText"
                placeholder="按下回车或点击按钮添加计划~"
                @focus="handleFocus"
                @blur="handleBlur"
                @keydown="handleKeyDown"
                auto-size
              ></a-textarea>
              <a-button class="ml-10" type="primary" @click="addTask">
                <template #icon><PlusOutlined /></template>
                添加</a-button
              >
            </div>
            <div class="item-wrap" v-if="todoList && todoList.length !== 0">
              <div class="flex-center" style="height: 100%" v-if="loading">
                <a-spin size="large" tip="Loading..." />
              </div>
              <template v-else>
                <div
                  v-for="(item, index) of todoList"
                  :key="item.id"
                  :class="['todo-item mt-10', { finish: item.status === 1 }]"
                >
                  <a-checkbox
                    v-model:checked="item.checked"
                    @change="setTaskStatus(item)"
                  >
                    <div class="label">
                      {{ index + 1 }}、{{ item.content }}；
                    </div>
                  </a-checkbox>
                </div></template
              >
            </div>
            <div v-else class="empty flex">
              适度的休息是为了更好的努力，请不要有任何负罪感!
            </div>
          </div>

          <div class="thought flex-column">
            <div class="title flex">
              <a-button type="primary" @click="showDialog">
                <template #icon><EditOutlined /></template>
                {{ thought ? "我还想说..." : "记录此刻" }}</a-button
              >
            </div>
            <div class="content" v-if="thought">{{ thought }}</div>
            <div class="empty-content flex-center" v-else>
              <img src="../../assets/images/thought.svg" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div
      class="daily-work-mobile"
      :style="{
        display: mobileDisplay,
      }"
    >
      <div class="mobile-wrapper flex-column">
        <div class="calendar">
          <div class="month-year flex">
            <div class="month-info">
              <div class="month">
                <img src="../../assets/images/flag.svg" />
                <span class="month-text">{{ currentMonth }}</span>
              </div>
              <div class="month-text-chinese">{{ currentMonthText }}</div>
            </div>
            <div class="year">
              {{ currentYear }}
            </div>
          </div>
          <div class="weekday flex">
            <div
              v-for="(item, index) of weekList"
              :class="[
                'weekday-item',
                {
                  weekend: [5, 6].includes(index),
                  'ml-5': index !== 0,
                },
              ]"
              :key="item"
            >
              周{{ item }}
            </div>
          </div>

          <div class="days flex">
            <div
              v-for="(item, index) of days"
              :class="[
                'day-item mt-5',
                {
                  active: currentDate === item.completeDay,
                },
              ]"
              :key="item.completeDay"
              @click="setDay(item)"
              :style="{
                color: item.currentMonth ? '' : '#f5e7cb',
                backgroundColor: item.currentMonth ? '' : '#fff',
              }"
            >
              <div class="day-status flex-column-center">
                <span class="day">{{ item.day }}</span>
                <template v-if="item.day <= todayValue">
                  <a-tooltip v-if="item.status === 1" color="green">
                    <template #title>计划都完成啦!</template>
                    <CheckOutlined />
                  </a-tooltip>
                  <a-tooltip v-else-if="item.status === 0" color="red">
                    <template #title>好像有些遗漏哦~</template>
                    <FrownOutlined />
                  </a-tooltip>
                </template>
              </div>
              <div class="todo-num">
                <i class="iconfont icon--Todo-List"></i>
                <span>{{ item.num || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="add-wrapper flex mt-10">
          <a-input
            v-model:value="taskText"
            placeholder="添加今日计划~"
            allow-clear
          />
          <PlusOutlined class="ml-5" @click="addTask" />
        </div>

        <div class="todo-list no-scroll-bar mt-15" :style="todoStyle">
          <div class="list-wrap" v-if="todoList && todoList.length !== 0">
            <div v-if="loading" class="flex-center">
              <a-spin size="large" tip="Loading..." />
            </div>
            <template v-else>
              <div
                v-for="(item, index) of todoList"
                :key="item.id"
                :class="[
                  'todo-item',
                  { 'mt-10': index !== 0, finish: item.status === 1 },
                ]"
              >
                <a-checkbox
                  v-model:checked="item.checked"
                  @change="setTaskStatus(item)"
                >
                  <div class="label">{{ index + 1 }}、{{ item.content }}；</div>
                </a-checkbox>
              </div></template
            >
          </div>
        </div>
      </div>
    </div>
  </div>

  <a-modal
    v-model:open="dialogShow"
    title="今日感悟"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="input-wrap">
      <a-textarea
        class="mt-10"
        v-model:value="thoughtValue"
        placeholder="你可以在此记录今天的想法、计划若没完成的原因，亦或是任何你想说的话······"
        :rows="6"
      />
    </div>
  </a-modal>
</template>

<script setup>
import { computed, onBeforeUnmount, onMounted, ref, createVNode } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  CheckOutlined,
  FrownOutlined,
  EditOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";

import {
  getDailyPlan,
  addDailyPlan,
  getDailyTotal,
  updateDailyPlan,
  getThought,
  commitThought,
  sqlTest,
} from "../../api/plan/daily";
import { getToday } from "@/utils/date";
import { debounce, validatePcMobile } from "../../utils/util";
import LinearButton from "../../components/ButtonComponent/linearButton.vue";
import FlashButton from "../../components/ButtonComponent/flashButton.vue";
import SendButton from "../../components/ButtonComponent/sendButton.vue";

const pcDisplay = ref("block");
const mobileDisplay = ref("none");

const weekList = ["一", "二", "三", "四", "五", "六", "日"];
const days = ref([]);
const todayValue = ref(null);
const currentYear = ref(null);
const currentMonth = ref(null);
const currentDate = ref(null);
let textObj = {
  1: "JANUARY",
  2: "FEBRUARY",
  3: "MARCH",
  4: "APRIL",
  5: "MAY",
  6: "JUNE",
  7: "JULY",
  8: "AUGUST",
  9: "SEPTEMBER",
  10: "OCTOBER",
  11: "NOVERMBER",
  12: "DECEMBER",
};
const currentMonthText = computed(() => textObj[currentMonth.value]);
function getDays() {
  return new Promise((resolve) => {
    let { year, month, day, completeDay } = getToday();
    currentYear.value = year;
    currentMonth.value = month;
    todayValue.value = day;
    currentDate.value = completeDay;
    // 填充上个月的天数
    var lastDayOfPrevMonth = new Date(year, month - 1, 0).getDate();
    let dayNum = new Date(year, month, 0).getDate();
    for (let i = 1; i <= dayNum; i++) {
      days.value.push({
        day: i,
        currentMonth: true,
        completeDay: `${year}-${("0" + month).slice(-2)}-${("0" + i).slice(
          -2
        )}`,
      });
    }
    let weekday = new Date(`${year}-${month}-01`).getDay();
    if (weekday === 0) {
      weekday = 7;
    }
    for (let i = 0; i < weekday - 1; i++) {
      days.value.unshift({
        day: lastDayOfPrevMonth,
        currentMonth: false,
        completeDay: `${month === 1 ? year - 1 : year}-${(
          "0" + (month === 1 ? "12" : month - 1)
        ).slice(-2)}-${("0" + lastDayOfPrevMonth).slice(-2)}`,
      });
      lastDayOfPrevMonth--;
    }
    let nextMonth = 35 - days.value.length;
    for (let i = 1; i <= nextMonth; i++) {
      days.value.push({
        day: i,
        currentMonth: false,
        completeDay: `${month === 12 ? year + 1 : year}-${(
          "0" + (month === 12 ? 1 : month + 1)
        ).slice(-2)}-${("0" + i).slice(-2)}`,
      });
    }
    resolve();
  });
}
function setDay(item) {
  if (!item.currentMonth) return;
  currentDate.value = item.completeDay;
  getList();
  getThoughtItem();
}

const isTextareaFocus = ref(false);
const handleFocus = () => {
  isTextareaFocus.value = true;
};
const handleBlur = () => {
  isTextareaFocus.value = false;
};
const handleKeyDown = (e) => {
  if (e.keyCode === 13) {
    e.preventDefault();
  }
};
const taskText = ref(null);
const addTask = debounce(addTaskApi, 2000, true);
function addTaskApi() {
  if (!taskText.value) {
    message.warning("你的输入框好像空空如也呢~");
    return;
  }
  const unwantedCharacters = [",", "，", ";", "；", "、", "。", "."];
  let lastChar = taskText.value.slice(-1);
  if (unwantedCharacters.includes(lastChar)) {
    taskText.value = taskText.value.slice(0, -1);
  }
  addDailyPlan({
    content: taskText.value,
    date: currentDate.value,
  }).then((res) => {
    if (res.code === 0) {
      taskText.value = "";
      getList();
      getTotalList();
    }
  });
}

const todoList = ref([]);
const loading = ref(false);
function getList() {
  let params = {
    date: currentDate.value,
  };
  loading.value = true;
  getDailyPlan(params).then((res) => {
    loading.value = false;
    if (res.code === 0) {
      res.data.forEach((item) => {
        item.checked = item.status === 1;
      });
      todoList.value = res.data;
    }
  });
}

function getThoughtItem() {
  let params = {
    date: currentDate.value,
  };
  getThought(params).then((res) => {
    if (res.code === 0) {
      thought.value = res.data;
    }
  });
}

function getTotalList() {
  getDailyTotal().then((res) => {
    if (res.code === 0) {
      days.value.forEach((item) => {
        let val = res.data.find((r) => r.date === item.completeDay);
        if (val) {
          item.num = val.num;
          item.status = val.status;
        }
      });
    }
  });
}

onMounted(() => {
  let isMobile = validatePcMobile();
  if (isMobile) {
    pcDisplay.value = "none";
    mobileDisplay.value = "block";
  } else {
    pcDisplay.value = "block";
    mobileDisplay.value = "none";
  }

  sqlTest().then((res) => {
    console.log(res, " =====474");
  });
  getDays().then(() => {
    getTotalList();
    getList();
    getThoughtItem();
  });

  window.addEventListener("keydown", (e) => {
    if (e.keyCode === 13) {
      isTextareaFocus.value && addTask();
    }
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("keydown", null);
});

const todoStatus = {
  finish: {
    text: "当天的计划已经全部完成啦，enjoy yourself!",
    color: "#00a3a6",
  },
  todo: {
    text: "当天的计划还没完成，加油!",
    color: "#c47ea6",
  },
  relax: {
    color: "transparent",
  },
};
let currentStatus = computed(() => {
  if (todoList.value.length === 0) {
    return "relax";
  } else {
    let some = todoList.value.some((item) => item.status === 0);
    return some ? "todo" : "finish";
  }
});
const todoStyle = computed(() => {
  return {
    borderColor: todoStatus[currentStatus.value].color,
  };
});
function setTaskStatus(item) {
  loading.value = true;
  updateDailyPlan({
    status: item.checked ? 1 : 0,
    id: item.id,
    date: item.date,
  }).then((res) => {
    loading.value = false;
    if (res.code === 0) {
      message.success(
        item.checked ? "太棒了，又完成了一项计划!" : "是不是不小心点错了呢~"
      );
      getList();
      getTotalList();
    }
  });
}

const dialogShow = ref(false);
const thoughtValue = ref(null);
const showDialog = () => {
  thoughtValue.value = thought.value;
  dialogShow.value = true;
};
const thought = ref(null);
const confirmLoading = ref(false);
function handleOk() {
  if (!thoughtValue.value) {
    message.warning("想好了再来吧，没有人说这个一定要写~");
    return;
  }
  confirmLoading.value = true;
  commitThought({
    thought: thoughtValue.value,
    date: currentDate.value,
  }).then((res) => {
    confirmLoading.value = false;
    if (res.code === 0) {
      message.success("想法会消失，文字会永远存在!");
      getThought({
        date: currentDate.value,
      }).then((res1) => {
        if (res1.code === 0) {
          thought.value = res1.data;
          dialogShow.value = false;
        }
      });
    }
  });
}

function handleCancel() {
  if (!thoughtValue.value) {
    dialogShow.value = false;
    return;
  }
  dialogShow.value = true;
  Modal.confirm({
    icon: () => createVNode(ExclamationCircleOutlined),
    content: () => createVNode("div", {}, "内容还没有保存，确认要关闭嘛?"),
    onOk() {
      thoughtValue.value = "";
      dialogShow.value = false;
    },
    onCancel() {
      console.log("Cancel");
    },
  });
}

// mobile
const mobileDate = ref(dayjs(new Date()));
</script>

<style scoped lang="less">
.daily-work {
  height: 100%;
  padding: 16px;
  font-size: 16px;

  .wrapper {
    height: 100%;
    width: 100%;
    margin: 0 auto;
    background-color: #ffffffad;
    border-radius: 16px;

    .title {
      font-size: 60px;
      padding: 16px 0 0 36px;
    }

    .content-wrap {
      .calendar {
        margin: 36px 0 0 18px;
        width: 604px;
        box-sizing: content-box;
        border: 1px solid #f5e7cb;
        border-radius: 24px;
        background-color: #fff;
        box-shadow: 0 0 5px #ddd;

        .month-year {
          justify-content: space-between;

          .month {
            position: relative;

            img {
              margin-top: -5px;
              margin-left: -8px;
              width: 64px;
              height: 64px;
            }

            &-text {
              position: absolute;
              left: 16px;
              top: 4px;
              font-size: 32px;
              color: #fff;
            }
          }

          .month-text-chinese {
            font-size: 48px;
          }

          .year {
            color: #deefee;
            font-size: 100px;
          }
        }

        .weekday-item {
          background-color: #c47ea6;
          color: #fff;
          padding: 5px 25px;
          border-radius: 8px;
          width: 82px;

          &.weekend {
            background-color: #00a3a6;
          }
        }

        .days {
          flex-wrap: wrap;

          .day-item {
            border: 1px solid #f5e7cb;
            background-color: #fff;
            color: #333;
            font-weight: bold;
            border-radius: 8px;
            width: 82px;
            aspect-ratio: 16 / 9;
            cursor: pointer;
            transition: all 0.5s;

            &:nth-child(7n - 1) {
              background-color: #ddeff0;
              color: #00a3a6;
            }
            &:nth-child(7n) {
              background-color: #ddeff0;
              color: #00a3a6;
            }

            &.active {
              background-color: #f8d5ea;
              color: #c47ea6;
            }

            .day-status {
              justify-content: space-between;

              :deep(.anticon) {
                font-size: 12px;
              }
            }

            .todo-num {
              margin: 3px 0 20px 0;
              font-size: 14px;
              font-weight: normal;
              text-align: center;

              span {
                margin-left: 2px;
              }
            }
          }
        }
      }

      .todo-list {
        flex: 1;
        margin: 36px;
        margin-bottom: 0;
        margin-right: 0;
        padding: 10px 25px;
        border-radius: 24px;
        border: 1px solid #00a3a6;
        box-shadow: 0 0 5px #ccc7c7;

        .tips {
          text-align: center;
        }

        .item-wrap {
          flex: 1;
          max-height: 600px;
          overflow-y: auto;

          .todo-item {
            :deep(.ant-checkbox-wrapper) {
              .ant-checkbox {
                align-self: flex-start;
                margin-top: 4px;
              }
            }

            &.finish {
              .label {
                text-decoration: line-through;
                transition: all 0.5s;
              }
            }
          }
        }

        .empty {
          flex: 1;
          background: url(../../assets/images/relax.png) no-repeat;
          background-size: contain;
          align-items: flex-end;
          letter-spacing: 1px;
          font-size: 14px;
          justify-content: center;
        }
      }

      .thought {
        flex: 1;
        border-radius: 24px;
        border: 1px solid #00a3a6;
        box-shadow: 0 0 5px #ccc7c7;
        margin: 36px;
        margin-bottom: 0;
        padding: 10px 25px;

        .title {
          padding: 0;
          font-size: 24px;
          justify-content: space-between;
        }

        .content {
          flex: 1;
          max-height: 600px;
          text-indent: 32px;
          white-space: wrap;
          width: 100%;
          overflow-y: auto;
          padding: 16px;
          padding-left: 0;
          padding-top: 0;
          margin-top: 16px;
          letter-spacing: 1px;
        }

        .empty-content {
          flex: 1;
        }
      }
    }
  }

  &-mobile {
    height: 100%;

    .mobile-wrapper {
      height: 100%;
      padding-bottom: 16px;
      overflow-y: hidden;

      .calendar {
        width: 100%;
        border: 1px solid #f5e7cb;
        border-radius: 12px;
        background-color: #fff;
        padding: 8px;

        .month-year {
          justify-content: space-between;

          .month {
            position: relative;

            img {
              width: 24px;
              height: 24px;
            }

            &-text {
              position: absolute;
              left: 9px;
              top: 4px;
              font-size: 12px;
              color: #fff;
            }
          }

          .year {
            color: #deefee;
            font-size: 24px;
          }
        }

        .weekday-item {
          background-color: #c47ea6;
          color: #fff;
          border-radius: 4px;
          font-size: 8px;
          width: calc((100% - 30px) / 7);
          padding: 3px 4px;
          text-align: center;

          &.weekend {
            background-color: #00a3a6;
          }
        }

        .days {
          flex-wrap: wrap;

          .day-item {
            border: 1px solid #f5e7cb;
            background-color: #fff;
            color: #333;
            border-radius: 4px;
            font-size: 8px;
            text-align: center;
            transition: all 0.5s;
            width: calc((100% - 30px) / 7);
            padding: 3px 4px;
            margin-left: 5px;

            &:nth-child(7n - 6) {
              margin-left: 0;
            }

            &:nth-child(7n) {
              margin-left: 4.8px;
            }

            &:nth-child(7n - 1) {
              background-color: #ddeff0;
              color: #00a3a6;
            }
            &:nth-child(7n) {
              background-color: #ddeff0;
              color: #00a3a6;
            }

            &.active {
              background-color: #f8d5ea;
              color: #c47ea6;
            }

            .day-status {
              justify-content: space-between;

              :deep(.anticon) {
                font-size: 7px;
              }
            }
          }
        }
      }

      .add-wrapper {
      }

      .todo-list {
        background-color: #fff;
        padding: 8px;
        border-radius: 8px 8px 0 0;
        flex: 1;
        overflow: auto;
        border: 1px solid #000;
      }
    }
  }
}
</style>
